﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Sunyi.Project.WebPoint.DataContract;

namespace Sunyi.Project.WebPoint.DataAccessController
{
    public partial class RoleDaoController
    {
        public Role SelectByName(string roleName)
        {
            Role role = null;

            Dictionary<Guid, object> roles = CacheProvider.Instance.Get<Role>();

            foreach (object obj in roles.Values)
            {
                Role item = obj as Role;

                if (item != null && item.RoleName == roleName)
                {
                    role = item;
                    break;
                }
            }

            if (role == null)
            {
                role = dao.SelectByName(roleName);
            }

            if (role != null)
            {
                dao.FillPermissions(role);
                CacheProvider.Instance.Add<User>(role.Id, role);
            }

            return role;
        }

        public Collection<Role> SelectAll(bool fillRolePermisson)
        {
            Collection<Role> items = dao.SelectAll();

            if (fillRolePermisson)
            {
                CacheProvider.Instance.Clear<Role>();
                foreach (var item in items)
                {
                    dao.FillPermissions(item);
                    CacheProvider.Instance.Add<Role>(item.Id, item);
                }
            }

            return items;
        }

        public int SearchCount(string roleName, bool isActive)
        {
            return dao.SearchCount(roleName, isActive);
        }

        public Collection<Role> Search(string roleName, bool isActive, int pageIndex, int pageSize)
        {
            return dao.Search(roleName, isActive, pageIndex, pageSize);
        }
    }
}
